package com.qf.factory;

import com.qf.service.AccountService;
import com.qf.service.impl.AccountServiceImpl;
import com.qf.util.TransactionManager;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @ClassName BeanFactory
 * @Description TODO
 * @Author Windy
 * @Date 2022/8/31 15:00
 * @Version 1.0
 **/
public class BeanFactory {

    AccountService accountService;

    TransactionManager tansactionManager;

    public void setAccountService(AccountService accountService) {
        this.accountService = accountService;
    }

    public void setTansactionManager(TransactionManager tansactionManager) {
        this.tansactionManager = tansactionManager;
    }

    public AccountService getAccountService(){
      AccountService o =(AccountService)  Proxy.newProxyInstance(accountService.getClass().getClassLoader(), AccountServiceImpl.class.getInterfaces(), new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                try {
                    if ("transfer".equals(method.getName())){
                        tansactionManager.beginTransaction();
                        method.invoke(accountService,args);
                        tansactionManager.commitTransaction();
                    }
                }catch (Exception e) {
                    tansactionManager.rollbackTransaction();
                    e.printStackTrace();
                }finally {
                    tansactionManager.releaseTransaction();
                }
                return null;
            }
        });

        return o;
    }
}
